package com.small.os.minio.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 * @author wangguochao
 */
@Component
public class MetaHandler implements MetaObjectHandler {


    /**
     * 新增数据执行
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String account = null;
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            account = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        if (metaObject.hasSetter("created")) {
            this.setFieldValByName("created",LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasSetter("updated")) {
            this.setFieldValByName("updated", LocalDateTime.now(), metaObject);
        }
        if (account == null) {
            return;
        }
        if (metaObject.hasSetter("createBy")) {
            this.setFieldValByName("createBy", account, metaObject);
        }
        if (metaObject.hasSetter("lastModifiedBy")) {
            this.setFieldValByName("lastModifiedBy", account, metaObject);
        }
    }

    /**
     * 更新数据执行
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String account = null;
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            account = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        }
        if (metaObject.hasSetter("updated")) {
            this.setFieldValByName("updated",  LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasSetter("lastModifiedBy")) {
            this.setFieldValByName("lastModifiedBy", account, metaObject);
        }
    }

}
